package com.saturn.auth;

import java.sql.Connection;

import org.json.JSONObject;

import com.saturn.app.db.DymaticCondition;
import com.saturn.app.db.ITransaction;
import com.saturn.app.db.ListData;
import com.saturn.app.db.ORMapping;
import com.saturn.app.db.ResultORMapping;
import com.saturn.app.db.SimpleDaoTemplate;
import com.saturn.app.exception.BSException;

public class Organization {

	private String id;
	private String name;
	private String description;
	private String parentId;

	private static ORMapping<Organization> mapping = new ResultORMapping<Organization>();

	public static int add(Organization organization) {
		if (get(organization.getId()) != null) {
			throw new BSException("组织结构ID重复,id=" + organization.getId());
		}

		String parentId = organization.getParentId();
		if (parentId != null && !"".equals(parentId.trim())) {
			return SimpleDaoTemplate.update(
					"INSERT INTO auth_organizations VALUES(?, ?, ?, ?)",
					organization.getId(), organization.getName(),
					organization.getDescription(), organization.getParentId());
		}

		return SimpleDaoTemplate
				.update("INSERT INTO auth_organizations(id, name, description) VALUES(?, ?, ?)",
						organization.getId(), organization.getName(),
						organization.getDescription());
	}

	public static int edit(Organization organization) {
		String parentId = organization.getParentId();
		if (parentId != null && !"".equals(parentId.trim())) {
			return SimpleDaoTemplate
					.update("UPDATE auth_organizations SET name = ?, description = ?, parentId = ? WHERE id = ?",
							organization.getName(),
							organization.getDescription(),
							organization.getParentId(), organization.getId());
		}

		return SimpleDaoTemplate
				.update("UPDATE auth_organizations SET name = ?, description = ? WHERE id = ?",
						organization.getName(), organization.getDescription(),
						organization.getId());
	}

	public static Organization get(String id) {
		return SimpleDaoTemplate.queryOne(
				"SELECT * FROM auth_organizations WHERE 1 = 1",
				new DymaticCondition().addCondition("and id = '?'", id),
				mapping, Organization.class);
	}

	public static ListData<Organization> getOrganizations(
			Organization organization, String start, String offset,
			String orderBy, String order) {

		return SimpleDaoTemplate.query(
				"SELECT * FROM auth_organizations WHERE 1 = 1",
				new DymaticCondition().addSimpleCondition(organization, "id",
						"name", "description", "parentId").addCondition(
						"ORDER BY {0} {1}", orderBy, order), mapping,
				Organization.class, start, offset);
	}

	public static int updateOrganizationResource(final String organizationId,
			final String[] chekcedIds) {

		return SimpleDaoTemplate.update(new ITransaction() {

			public int execute(Connection connection) {
				SimpleDaoTemplate
						.update(connection,
								"DELETE FROM auth_re_organization_resource WHERE organizationId = ?",
								organizationId);
				StringBuffer buffer = new StringBuffer();
				buffer.append("insert into auth_re_organization_resource values");

				for (int i = 0; i < (chekcedIds.length); i++) {
					buffer.append("('");
					buffer.append(organizationId + "','" + chekcedIds[i]);
					buffer.append("'),");
				}
				String sql = buffer.toString().substring(0,
						buffer.toString().length() - 1);

				return SimpleDaoTemplate.update(connection, sql, (String) null);
			}
		});
	}

	public static int remove(final String id) {

		return SimpleDaoTemplate.update(
				"DELETE FROM auth_organizations WHERE id = ?", id);

	}

	public static void removes(String[] ids) {
		if (ids != null) {
			for (String id : ids) {
				remove(id);
			}
		}
	}

	public static int removeAllResource(String id) {
		return SimpleDaoTemplate
				.update("DELETE FROM auth_re_organization_resource WHERE organizationId = ?",
						id);
	}

	public static int removeUser(String organizationId, String userId) {
		return SimpleDaoTemplate
				.update("DELETE FROM auth_re_organization_user WHERE organizationId = ? and userId = ?",
						organizationId, userId);
	}

	public static void removeUsers(String organizationId, String[] userIds) {
		if (userIds != null) {
			for (String userId : userIds) {
				removeUser(organizationId, userId);
			}
		}
	}

	public Organization() {
	}

	public Organization(String id, String name, String description,
			String parentId) {
		this.id = id;
		this.name = name;
		this.description = description;
		this.parentId = parentId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	@Override
	public String toString() {
		return new JSONObject(this).toString().replace("parentId", "_parentId");
	}
}
